import { Message } from 'tinper-bee';
import axios from "axios";
import { actions } from 'mirrorx';
import cloneDeep from 'lodash.clonedeep';
import { type } from 'os';
import { number } from 'prop-types';
import { encode } from 'querystring';


export const success = (msg) => {
    Message.create({ content: msg, color: 'success', duration: 10 });
}

export const Error = (msg) => {
    Message.create({ content: msg, color: 'danger', duration: 20 });
}

export const Warning = (msg) => {
    Message.create({ content: msg, color: 'warning', duration: 10 });
}

export const Info = (msg) => {
    Message.create({ content: msg, color: 'info', duration: 3 });
}
/**
 * 数据返回统一处理函数
 * @param {*} response
 * @param {*} successMsg 成功提示
 */

/**
* 数据返回统一处理函数
* @param {*} response
* @param {*} successMsg 成功提示
*/
export const processData1 = (response, successMsg) => {
    if (typeof response != 'object') {
        Error('数据返回出错：1、请确保服务运行正常；2、请确保您的前端工程代理服务正常；3、请确认您已在本地登录过应用平台');
        return;
    }
    if (response.status == '401') {
        Error(`错误:${(response.data.message)}`);
        return;
    }
    let data, code;
    if (response.status == '200') {
        data = response.data;
        code = data.code;
        if (code == 1) {
            if (successMsg) {
                success(successMsg || data.message && data.message);
            }
            return data;
        } else {
            Error(`${data.message || '数据返回出错'}`);
        }
    } else {
        Error(`${response.data.message || '数据返回出错'}`);
        return;
    }
};

export const renderState = (state) => {
    switch(state) {
        case 0: return "自由";
        case 1: return "提交";
        case 2: return "审批中";
        case 3: return "审批通过";
        default: return "其他";
    }
}

export const renderEnable = (state) => {
    switch(state) {
        case 0: return "未启用";
        case 1: return "启用";
        case 2: return "停用";
    }
}

export const processData2 = (response, successMsg) => {
    if (typeof response != 'object') {
        Error('数据返回出错：1、请确保服务运行正常；2、请确保您的前端工程代理服务正常；3、请确认您已在本地登录过应用平台');
        return;
    }
    if (response.status == '401') {
        Error(`错误:${(response.data.message)}`);
        return;
    }
    let data, code;
    if (response.status == '200') {
        data = response.data;
        if (successMsg) {
            success(successMsg || data.message && data.message);
        }
        return data;
    } else {
        Error(`${response.data.message || '数据返回出错'}`);
        return;
    }
};
export const processData = (response, successMsg) => {
    if (typeof response != 'object') {
        Error('数据返回出错：1、请确保服务运行正常；2、请确保您的前端工程代理服务正常；3、请确认您已在本地登录过应用平台');
        return;
    }
    if (response.status == '401') {
        Error(`错误:${(response.data.message)}`);
        return;
    }
    let data, code;
    if (response.status == '200') {
        data = response.data;
        code = data.code;
        let status = data.status;
        if (status == 1) {
            if (successMsg) {
                success(data.message && data.message || successMsg);
            }
            if (typeof (data.data) == "number") {
                return data.data;
            } else {
                return data.data || data;
            }

        } else {
            Error(`${data.message || '数据返回出错'}`);
        }
    } else {
        Error(`${response.data.message || '数据返回出错'}`);
        return;
    }
}

/**
 * param拼接到url地址上
 * @param {*} url
 * @param {*} params
 * @param {*} prefix
 */
export const paramToUrl = (url, params, prefix) => {
    if (!prefix) prefix = '';
    if (url.indexOf('?') == -1) {
        url += '?r=' + Math.random();
    }
    for (let attr in params) {
        if ((attr == 'pageIndex') || (attr == 'pageSize')) {
            url += '&' + attr + '=' + params[attr];
        } else {
            url += '&' + prefix + attr + '=' + params[attr];
        }
    }
    return url;
}

/**
 * json转换指定的前缀
 * @param {JSON} json
 * @param {JSON} prefix
 */
export const jsonToUrl = (json, prefix = "search_") => {
    let obj = {};
    for (let attr in json) {
        if ((attr == 'pageIndex') || (attr == 'pageSize')) {
            obj[`${attr}`] = json[attr];
        } else {
            obj[`${prefix}${attr}`] = json[attr];
        }
    }
    return obj;
}

// 后台乱码转换
export const convert = (text) => {
    let element = document.createElement("p");
    element.innerHTML = text;
    let output = element.innerText || element.textContent;
    element = null;
    return output;
}

export const setCookie = (name, value, options) => {

    options = options || {};
    if (value === null) {
        value = '';
        options.expires = -1;
    }
    let expires = '';
    if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
        let date;
        if (typeof options.expires == 'number') {
            date = new Date();
            date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
        } else {
            date = options.expires;
        }
        expires = '; expires=' + date.toUTCString();
    }
    let path = options.path ? '; path=' + options.path : '';
    let domain = options.domain ? '; domain=' + options.domain : '';
    let s = [cookie, expires, path, domain, secure].join('');
    let secure = options.secure ? '; secure' : '';
    let c = [name, '=', encodeURIComponent(value)].join('');
    let cookie = [c, expires, path, domain, secure].join('')
    document.cookie = cookie;

}

export const getCookie = (name) => {

    let cookieValue = null;
    if (document.cookie && document.cookie != '') {
        let cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            let cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    // 按照总设部规范，调整为下划线
    // if (typeof cookieValue != 'undefined' && cookieValue != null) {
    //     cookieValue = cookieValue.replace(/-/, "_");
    // }
    return cookieValue;
}


/**
 * 生成唯一字符串
 */
export function uuid() {
    const s = [];
    const hexDigits = '0123456789abcdef';
    for (let i = 0; i < 36; i += 1) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = '4';
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    s[8] = '-';
    s[13] = '-';
    s[18] = '-';
    s[23] = '-';
    return s.join('');
}


/**
 * 导出excel 后端导出，通过post方式
 *
 */
export function exportExcelPost(url, data) {
    axios({
        method: 'post',
        url: url,
        data: data,
        responseType: 'blob'
    }).then((res) => {
        const content = res.data;
        const blob = new Blob([content]);
        const fileName = "导出数据.xls";
        const selfURL = window[window.webkitURL ? 'webkitURL' : 'URL'];
        let elink = document.createElement('a');
        if ('download' in elink) {
            elink.download = fileName;
            elink.style.display = 'none';
            elink.href = selfURL['createObjectURL'](blob);
            document.body.appendChild(elink);

            // 触发链接
            elink.click();
            selfURL.revokeObjectURL(elink.href);
            document.body.removeChild(elink)
        } else {
            navigator.msSaveBlob(blob, fileName);
        }
    })
}


/**
 *
 * @description 树节点添加子数据
 * @export
 * @param {array} [parentArray=[]]
 * @param {array} [childArray=[]]
 * @returns
 */
export function addChild(parentArray = [], childArray = []) {

    let parentLen = parentArray.length;
    if (parentLen == 0 || childArray.length == 0) {
        return [];
    }
    let parentId = childArray[0].parentId;

    for (let i = 0; i < parentLen; i++) {
        let item = parentArray[i];
        if (item.id === parentId) {
            item['isSon'] = 2;
            let newChildren = [];
            if (Array.isArray(item['children'])) {
                let isObtain = item['children'].some(item => {
                    return item['id'] == (childArray.length && childArray[0]['id']);
                });

                if (!isObtain) {
                    newChildren = deepClone(item['children']).concat(childArray);
                } else {
                    newChildren = deepClone(item['children']);
                }

            } else {
                newChildren = childArray;
            }
            /* let newChildren = (typeof item['children'] === 'undefined' && !item['children']) ? childArray : deepClone(item['children']).concat(childArray);
            item['children'] = newChildren; */
            item['children'] = newChildren;
            break;
        } else {
            let temp = item['children'];
            if (typeof temp !== 'undefined' && Array.isArray(temp) && temp.length) {
                console.log("item['children']", item['children']);
                setTimeout(function () {
                    addChild(item['children'], childArray);
                }, 0);

            }
        }
    }

    return parentArray;
}

// 处理子节点,type为0 表示查找; type为1 表示删除
export function handleChild(parentArray, child, type) {
    let parentLen = parentArray.length,
        resChild = {};
    // isDelete = false;

    for (let i = 0; i < parentLen; i++) {
        let item = parentArray[i];
        if (item.id == child.id) {
            if (type === 0) {
                resChild = item;
                return resChild;
            } else {
                parentArray.splice(i, 1);
                return true;
            }
        } else {
            if (typeof item['children'] !== 'undefined') {
                resChild = handleChild(item['children'], child, type);

                // 查找节点
                if (type == 0 && (Object.keys(resChild).length > 0)) {
                    return resChild;
                }

                if (type === 1 && typeof resChild === 'boolean' && resChild) {
                    if (!item['children'].length) {
                        item['isSon'] = 1;
                    }
                }

            }
        }
    }

    return resChild;
}


// 数组深克隆
export function deepClone(data) {
    if (isEmptyObj(data)) {
        return JSON.parse(JSON.stringify(data));
    }
    return data;

}

// 数组深克隆
export function translateApprove(data) {
    switch (data) {
        case "1": return "自由"; break;
        case "2": return "审批通过"; break;
        case "3": return "冻结"; break;
        case "4": return "关闭"; break;
        case "5": return "失效"; break;
        case "7": return "审批中"; break;
        case "8": return "审批不通过"; break;

    }
}

/**
 * 后端数据附加key
 * @param {*} arrayobject
 */
export function resultDataAdditional(arrayobject) {
    if (Array.isArray(arrayobject)) {
        return Array.from(arrayobject, (x, i) => ({ ...x, key: i }))

    } else {
        return [];
    }
}


/**
 * 深度 obj 合并
 * const a = {a: 1, b: 2, c: 3, d: {key: 2, value: 4}, e: [1, 2, 3]};
 * const b = {a: 3, d: {key:4}, e: [4, 5]};
 * 1. 如果值为{},则覆盖
 * 2. 如果数组全覆盖
 * 3 否则深度
 * @param def
 * @param obj
 * @returns {*}
 */
export function deepAssign(preData, nextData) {
    for (const preKey in preData) {
        const preChildrenKeys = Object.keys(preData[preKey]);
        let nextChildrenKeys = 0;
        if (nextData[preKey] && !Array.isArray(preData[preKey])) {
            nextChildrenKeys = Object.keys(nextData[preKey]);
        }
        if (preChildrenKeys.length > 0 && nextChildrenKeys.length > 0) {
            deepAssign(preData[preKey], nextData[preKey]);
        } else {
            const tempNextValue = nextData[preKey];
            if (tempNextValue !== undefined) {
                preData[preKey] = tempNextValue;
            }
        }
    }
    return preData;
}

/**
 * 对请求回来带有分页的数据 解构，拼装
 * @param obj
 * @param param
 * @returns {{list: *, pageIndex: *, totalPages: *, total: *, pageSize: *}}
 */
export function structureObj(obj, param) {
    const { content, number, totalPages, totalElements, size } = obj;
    let { pageSize } = param;
    if (!pageSize) {
        pageSize = size;
    }
    return {
        list: content,
        pageIndex: number + 1,
        totalPages: totalPages,
        total: totalElements,
        pageSize,// 结构请求的pageSize,
    };

}

/**
 * 初始化 state 里的带有分页的 obj
 * @param obj
 * @returns {{list: Array, pageIndex: number, totalPages: number, total: number, pageSize: *}}
 */
export function initStateObj(obj) {
    const { pageSize } = obj;
    return {
        list: [],
        pageIndex: 0,
        totalPages: 0,
        total: 0,
        pageSize,
    };

}


export function clearTrimObj(data) {
    for (const key in data) {
        const keys = Object.keys(data[key]);
        if (keys.length > 0) {
            if (Array.isArray(data[key])) {
                for (const [index, ele] of data[key].entries()) {
                    if (typeof ele === 'object') {
                        clearTrimObj(ele);
                    } else {
                        data[key][index] = ele.trim();
                    }
                }
            } else {
                clearTrimObj(data[key]);
            }

        } else {
            data[key] = data[key].trim();
        }
    }
    return data;
}


/**
 * 获得按钮切换状态
 *
 * @param {string} action 按钮类型
 * @param {string} status 按钮状态
 * @returns Object
 */
export function getButtonStatus(action, status) {
    let enabledObj = {};
    switch (status) {
        case 'view':
            enabledObj = {
                add: false,
                edit: false,
                del: false,
                down: false,
                import: false,
                export: false,
                save: true,
                cancel: true
            }

            return enabledObj[action];
        case 'new':
            enabledObj = {
                add: false,
                edit: true,
                del: true,
                down: true,
                import: true,
                export: true,
                save: false,
                cancel: false
            }
            return enabledObj[action];
        case 'edit':
            enabledObj = {
                add: true,
                edit: true,
                del: true,
                down: true,
                import: true,
                export: true,
                save: false,
                cancel: false
            }
            return enabledObj[action];
        default:
            break;
    }
}


/**
 * 过滤脏数据按照|分割的字段
 *
 * @param {object} data
 * @returns
 */
export function filterDataParam(data) {
    let keys = Object.keys(data);
    let values = Object.values(data);
    let arr = [];
    for (let i = 0; i < keys.length; i++) {
        if (keys[i].indexOf('|') > -1) {
            let _key = keys[i].split('|')[0];//字段
            let _index = keys[i].split('|')[1];//当前对象索引
            let _value = values[i];//值
            if (typeof arr[_index] != 'object') {
                arr[_index] = {};
            }
            arr[_index][_key] = _value;
        }
    }
    return arr;
}

/**
 * 删除指定的key数据
 * @param {array} keyData - 选择的数组对象包含key
 * @param {array} res - 系统默认的list数据
 * @returns {array} - 处理后的数组对象数据，用于表数据
 */
export function delArrayByKey(keyData, res) {
    for (let keyItem of keyData) {
        for (let [index, ele] of res.entries()) {
            if (keyItem.key === ele.key) {
                res.splice(index, 1);
                break
            }
        }
    }
    return res;
}


/** 将新数组对象与旧数组相同对象删除
 * @param {array} arrayOld 旧数组对象
 * @param {array} arrayNew 新数组对象
 * @param {string} key  关联字段
 */
export function delListObj(arrayOld, arrayNew, key) {
    if (arrayNew.length === 0) { // 如果新数组为空 直接返回
        return arrayOld;
    }
    for (const eleNew of arrayNew) { // 将新数组对象与旧数组对象合并
        for (const [indexOld, eleOld] of arrayOld.entries()) { //
            if (eleOld[key] === eleNew[key]) {
                arrayOld.splice(indexOld, 1);
                break;
            }
        }
    }
    return arrayOld;

}


/** 将新数组对象与旧数组对象合并
 * @param {array} arrayOld 旧数组对象
 * @param {array} arrayNew 新数组对象
 * @param {string} key  关联字段
 */
export function mergeListObj(arrayOld, arrayNew, key) {
    if (arrayOld.length === 0) { // 如果old数组为空 直接返回
        return arrayNew;
    }
    for (const eleNew of arrayNew) { // 将新数组对象与旧数组对象合并
        let isHas = true;
        for (const [indexOld, eleOld] of arrayOld.entries()) { //
            if (eleOld[key] == eleNew[key]) {
                arrayOld[indexOld] = eleNew;
                isHas = false;
                break;
            }
        }
        if (isHas) {  // 旧数组没有找到
            arrayOld.push(eleNew);
        }

    }
    return arrayOld;
}


/**
 *
 * @description 排序属性设置
 * @export
 * @param {*} sortParam 排序参数对象数组
 * @returns {Array} 返回排序属性
 */
export function getSortMap(sortParam) {
    // 升排序
    const orderSortParam = sortParam.sort((a, b) => {
        return a["orderNum"] - b["orderNum"];
    })
    let sortMap = [];
    sortMap = orderSortParam.map((sortItem, index) => {
        const { order, field } = sortItem,
            tempObj = {}; // order 排序方式，field排序字段
        const direction = (order === 'ascend' ? "ASC" : "DESC"); //  前后端约定
        let property = field;
        if (field.includes("EnumValue")) {
            property = field.replace("EnumValue", ''); //去掉枚举尾标记，前后端约定
        }
        tempObj[property] = direction;
        return tempObj;
    })
    return sortMap;
}

/**
 *@description 获取分页数据
 *
 * @param {*} value
 * @param {*} type type为0标识为pageIndex,为1标识pageSize
 */
export function getPageParam(value, type, pageParams) {
    if (type === 0) {
        pageParams.pageIndex = value - 1;
    } else {
        //pageSize = value.toLowerCase() !== 'all' && value || 1;
        pageParams.pageSize = value || 10;
        pageParams.pageIndex = 0;
    }
    return pageParams

}

/**
 *@description 处理form的 validateFields 返回空格问题。
 * @param {*} 数据源
 */
export function getValidateFieldsTrim(values) {
    for (const key in values) {
        if (values.hasOwnProperty(key)) {
            const element = values[key];
            if (isString(element)) {
                values[key] = (values[key]).trim();
            }
        }
    }
    return values;
}

function isString(str) {
    return (typeof str == 'string') && str.constructor == String;
}
/**
 * @description 根据页面视口区域高度计算表格高度，以确定什么时候出滚动条
 * @returns {Number} height表格内容区高度
 */
export function getHeight() {
    let clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight),
        scrollHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
    let showHeight = (clientHeight < scrollHeight) && clientHeight || scrollHeight;
    return showHeight;
}

/**
 * 提取arr中某个字段
 * @param {arr} arr
 * @param {String} field
 */
export const getFieldsFromArr = (arr = [], field = '') => {
    let newArr = [];
    if (!arr.length && !field) return;

    arr.forEach(element => {
        newArr.push(element[field]);
    });
    return newArr;
}

export const exprotSearchUrl = (url, param) => {
    url = url + '?1=1';

    for (let attr in param.whereParams) {
        url += '&search_' + attr + '=' + param.whereParams[attr];

    }
    for (let attr1 in param.pageParams) {
        let paramattr;
        if (attr1 == "pageSize") paramattr = 'size';
        if (attr1 == "pageIndex") paramattr = 'page';
        url += '&' + paramattr + '=' + param.pageParams[attr1];

    }

    return url;
}
//处理时间 参照 persisStatus
export const onHandleChildObj = (values, flag, err) => {
    let data;
    for (let item in values) {
        //persisStatus处理
        //优先过滤日期格式
        if (values[item] && typeof values[item] === 'object' && values[item]._d) {
            values[item] = new Date(values[item]);
            values[item] = values[item].getTime();
        }

        if (values[item] && typeof values[item] === 'object' && values[item].constructor !== Array && values[item] !== {}) {
            //if(isEmptyObj(values[item])) {

            //}

            for (var key in values[item]) {
                if (values[item][key] && typeof values[item][key] === 'object' && values[item][key]._d) {
                    values[item][key] = values[item][key]._d.getTime();
                }
                data = onHandleRefObj(values[item][key], key, err);
                if (typeof values[item][key] === 'string' && values[item][key].indexOf("{") !== -1) {
                    let str = key.slice(0, key.length - 2);
                    values[item][key] = data["ref"].refpk;
                    values[item][`${str}Name`] = data["ref"].refname;
                    values[item][`${str}Code`] = data["ref"].refcode;
                }
                err = data["err"];
            }
        } else {
            data = onHandleRefObj(values[item], item, err);
            if (typeof values[item] === 'string' && values[item].indexOf("{") !== -1) {
                let str = item.slice(0, item.length - 2);
                values[item] = data["ref"].refpk;
                values[`${str}Name`] = data["ref"].refname;
                values[`${str}Code`] = data["ref"].refcode;
            }

            err = data["err"];
        }

    }
    flag == 0 ? values.persistStatus = 'new' : values.persistStatus = 'upd';
    return { values: values, err: err };

}

export const onHandleRefObj = (values, item, err) => {
    //参照处理
    let refpk, refname, refcode;
    if (typeof values === 'string' && values.indexOf("{") !== -1) {

        if (!JSON.parse(values)['refpk'] && JSON.parse(values)['require']) {
            if (!err) err = {};
            err[item] = true;
            refpk = null;
            refname = null;
            refcode = null;
        } else {
            refpk = JSON.parse(values)['refpk'];
            refname = JSON.parse(values)['refname'];
            refcode = JSON.parse(values)['refcode'];
        }


    }
    return { ref: { refpk: refpk, refname: refname, refcode: refcode }, err: err };
}

export const initValueString = (name, pk, requiredFlag, code, defaultValue) => {
    if (!pk) return defaultValue || null;

    let param = {
        refname: name || "",
        refpk: pk || "",
        refcode: code || "",
        require: requiredFlag || false
    }

    let STR = JSON.stringify(param);
    return STR;
}

export const isEmptyObj = (model) => {
    let hasProp = false;
    if (typeof model === "object" && !(model instanceof Array)) {
        for (let prop in model) {
            hasProp = true;
            break;
        }
        if (hasProp) {
            model = [model];
        } else {
            return false;
        }
    }
    return hasProp
}


{/*
param={
    pageParams: {
        pageIndex: 0,
        pageSize: 10,
    },
    // groupParams: [],
    whereParams: {}
}
searchField = [
    {

        enname: "code",
        zhname: "供应商编号",
        required: false,
        searchType:'like',
        type: "FormControl",
        edit: true
    }
]
*/}


export const handleSearchValue = (param, searchField) => {
    let searchValue = {};
    let values = param && param.whereParams || undefined;
    // searchValue = param.pageParams;
    // delete searchValue.pageSize;
    // delete searchValue.pageSize;
    searchValue.size = param.pageParams.pageSize;
    searchValue.page = param.pageParams.pageIndex;
    if (param.pageParams.searchExtend) {
        searchValue = Object.assign({}, searchValue, param.pageParams.searchExtend);
    }
    if (!isEmptyObj(values)) return searchValue;
    searchField.forEach(item => {
        //Object.keys(values).forEach(function(index){
        let Field = item.enname;
        let value = values[Field];
        if (Field.search("&") != -1){
            Field = Field.replace(/&/g, '.');
        }
        if (Field.search("&") != -1 && value && item.searchType) {
            Field = Field.replace(/&/g, '.');
            searchValue[`search_${item.searchType || 'LIKE'}_${Field}`] = item.searchType == 'LIKE' && `%${value}%` || value;
            return;
        }
        if (item.searchType == "like" && value) {
            searchValue[`search_LIKE_${Field}`] = `%${value}%`;
        }
        else if (item.searchType == "IN" && value) {
            searchValue[`search_IN_${Field}`] = value.join(",");
        }
        else if (item.type == "RangePicker" && value && value[0]) {

            let tmp0 = ((typeof (value[0]) == "string") ? (new Date(value[0]).getTime()) : (value[0]._d.getTime()));
            let tmp1 = ((typeof (value[1]) == "string") ? (new Date(value[1]).getTime()) : (value[1]._d.getTime()));

            if (item.timeFlag) {
                searchValue[`search_GTE_${item.rangeField[0]}_datetime`] = tmp0;
                searchValue[`search_LT_${item.rangeField[1]}_datetime`] = tmp1;
            } else {
                searchValue[`search_GTE_${item.rangeField[0]}_date`] = tmp0;
                searchValue[`search_LT_${item.rangeField[1]}_date`] = tmp1;
            }
        }
        else if (item.type == "InputNumberGroup" && value) {
            if (typeof Number(value[0]) == "number" && value[0] !== "") {
                searchValue[`search_GTE_${item.rangeField[0]}`] = value[0];
            }
            if (typeof Number(value[1]) == "number" && value[1] !== "") {
                searchValue[`search_LT_${item.rangeField[1]}`] = value[1];
            }

        }
        else if (item.type == "DatePicker" && value) {
            searchValue[`search_EQ_${Field}`] = value._d.getTime();
        }
        else if (item.type == "Radio" && !isNaN(Number(value))) {
            if (item.searchType == "nullStatus") {
                if(value==0){
                    searchValue[`search_NULL_${Field}`] = value;
                }else if(value==1){
                    searchValue[`search_NOTNULL_${Field}`] = value;
                }
            }else{
                searchValue[`search_EQ_${Field}`] = value;
            }
        }
        else if (item.type == "RefComponent" && value && JSON.parse(value)['refpk']) {
            let str = `${Field}`;
            let key;
            if (!item.realRef) {
                str = str.slice(0, str.length - 2) + '.id';
            }
            if (item.multiple) {
                key = `search_IN_${str}`;
            } else {
                key = `search_EQ_${str}`;
            }
            if (!item.codeRef) {
                searchValue[key] = JSON.parse(value)['refpk'];
            }else{
                searchValue[key] = JSON.parse(value)['refcode'];
            }
        }
        else if (item.type === "InputNumber" && !isNaN(Number(value))) {
            searchValue[`search_${item.searchType || "EQ"}_${Field}`] = value;
        }
        else if (item.type != "RefComponent" && value) {
            searchValue[`search_EQ_${Field}`] = value;
        }

    })

    return searchValue;
}

export const dealTreeList = (data=[]) => {
    if(!data) return [];
      // create a name: node map name=id parent=pid 
      var dataMap = data.reduce(function(map, node) {
        map[node.id] = node;
        return map;
      }, {});
      
      // create the tree array
      var tree = [];
      data.forEach(function(node) {
        // add to parent name=id parent=pid 
        var parent = dataMap[node.pid];
        if (parent) {
            // create child array if it doesn't exist
            (parent.children || (parent.children = []))
                // add node to child array
                .push(node);
        } else {
            // parent is null or missing
            tree.push(node);
        }
      });
    return tree;
}
export const handleGetDealSearchValue = (param={}, searchField) => {
    let searchValue = {};
    let values = param;
    // searchValue = param.pageParams;
    // delete searchValue.pageSize;
    // delete searchValue.pageSize;
    searchValue.size = param.size;
    searchValue.page = param.page;
    // if (param.pageParams.searchExtend) {
    //     searchValue = Object.assign({}, searchValue, param.pageParams.searchExtend);
    // }
    if (!isEmptyObj(param)) return {};
    searchField.forEach(item => {
        //Object.keys(values).forEach(function(index){
        let Field = item.enname;
        let value = values[Field];
        if (Field.search("&") != -1 && value) {
            Field = Field.replace(/&/g, '.');
            searchValue[`search_${item.searchType || 'LIKE'}_${Field}`] = item.searchType == 'LIKE' && `%${value}%` || value;
            return;
        }
        if (item.searchType == "like" && value) {
            searchValue[`search_LIKE_${Field}`] = `%${value}%`;
        }
        else if (item.searchType == "IN" && value) {
            searchValue[`search_IN_${Field}`] = value.join(",");
        }
        else if (item.type == "RangePicker" && value && value[0]) {

            let tmp0 = ((typeof (value[0]) == "string") ? (new Date(value[0]).getTime()) : (value[0]._d.getTime()));
            let tmp1 = ((typeof (value[1]) == "string") ? (new Date(value[1]).getTime()) : (value[1]._d.getTime()));

            if (item.timeFlag) {
                searchValue[`search_GTE_${item.rangeField[0]}_datetime`] = tmp0;
                searchValue[`search_LT_${item.rangeField[1]}_datetime`] = tmp1;
            } else {
                searchValue[`search_GTE_${item.rangeField[0]}_date`] = tmp0;
                searchValue[`search_LT_${item.rangeField[1]}_date`] = tmp1;
            }
        }
        else if (item.type == "InputNumberGroup" && value) {
            if (typeof Number(value[0]) == "number" && value[0] !== "") {
                searchValue[`search_GTE_${item.rangeField[0]}`] = value[0];
            }
            if (typeof Number(value[1]) == "number" && value[1] !== "") {
                searchValue[`search_LT_${item.rangeField[1]}`] = value[1];
            }

        }
        else if (item.type == "DatePicker" && value) {
            searchValue[`search_EQ_${Field}`] = value._d.getTime();
        }
        else if (item.type == "Radio" && !isNaN(Number(value))) {
            if (item.searchType == "nullStatus") {
                if(value==0){
                    searchValue[`search_NOTNULL_${Field}`] = value;
                }else if(value==1){
                    searchValue[`search_NULL_${Field}`] = value;
                }
            }else{
                searchValue[`search_EQ_${Field}`] = value;
            }
        }
        else if (item.type == "RefComponent" && value && JSON.parse(value)['refpk']) {
            let str = `${Field}`;
            let key;
            if (!item.realRef) {
                str = str.slice(0, str.length - 2) + '.id';
            }
            if (item.multiple) {
                key = `search_IN_${str}`;
            } else {
                key = `search_EQ_${str}`;
            }
            if (!item.codeRef) {
                searchValue[key] = JSON.parse(value)['refpk'];
            }else{
                searchValue[key] = JSON.parse(value)['refcode'];
            }
        }
        else if (item.type === "InputNumber" && !isNaN(Number(value))) {
            searchValue[`search_${item.searchType || "EQ"}_${Field}`] = value;
        }
        else if (item.type != "RefComponent" && value) {
            searchValue[`search_EQ_${Field}`] = value;
        }

    })

    return searchValue;
}

export const StringData = (data) => {
    let string = '';
    let searchParams = data.searchParams;
    if(JSON.stringify(searchParams) == "{}") delete data.searchParams
    Object.keys(data).forEach(function (item, i) {
        let temp = data[item];
        if (isEmptyObj(data[item])) {
            temp = JSON.stringify(temp);
            temp = encodeURI(temp);
        }
        let str = item + "=" + temp;
        (i != 0) ? (string += '&' + str) : (string += str);
    })

    return string;
}

/**
 * 时间戳转换
timestamp:时间戳
type:用以区分是时间还是日期
 * @param {String} timestamp
 * @param {String} type
 *
 */
export const ts2Formatter = (timestamp, type) => {
    var date = new Date(timestamp);

    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate());
    var h = ' ' + date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
    if(type == "month") return Y + (date.getMonth() + 1);
    return (type ? (Y + M + D + h + m + s) : (Y + M + D));
}

/**
 * 级联带出值
 *
 */
export const resetOfferRefCommon = (scope, relation, data=[], childType) => {
    // if (!data || !data[0]) return;
    let param = {};
    let field, refpk = "", refcode = "", refname = "";
    for (var i of relation) {
        if (!childType || childType.search("DataHeader") != -1) {
            field = i.ref;
        } else {
            field = `${childType}.${i.ref}`;
        }

        if (typeof (data) == "object") { //判断是参照过来的值
            if (!data) return;
            refpk = data[0] && data[0][i.refpk] || "";
            refname = data[0] && data[0][i.refname] || "";
            refcode = data[0] && data[0][i.refcode] || "";
            param[field] = (i.relationType == "ref") ? JSON.stringify({
                "refpk": refpk,
                "refname": refname,
                "refcode": refcode
            }) : refpk;
        } else if ("matchValue" in i && (i.matchValue == data || i.matchValue.toString().search(data.toString()) != -1)) {
            if ("value" in i) {
                refpk = i.value;
            } else {
                refpk = data
            }
            param[field] = refpk;
        } else {
            continue;
        }

    }
    //重置级联下级参照值
    scope.props.form.setFieldsValue(param);
}

/**
 * 级联带出值新
 *
 */
export const resetOfferRefCommon2 = (scope, relation, data, childType) => {
    let param = {};
    let field;

    for (var i of relation) {
        for (var j in i) {
            if (!childType || childType.search("DataHeader") != -1) {
                field = j;
            } else {
                field = `${childType}.${j}`;
            }

            let curren = i[j];
            if (data && data[0]) {
                param[field] = (typeof (curren) === "string") ? (data[0][curren]) : (JSON.stringify({
                    "refpk": data[0][curren.refpk],
                    "refname": data[0][curren.refname],
                    "refcode": data[0][curren.refcode]
                }));
            }
        }
    }
    //重置级联下级参照值
    scope.props.form.setFieldsValue(param);
}

/* 一个字段值的状态影响另外的字段或是模块的显示与否 */
export const manipulator = (scope, manipulation, data, Pool) => {
    let { btnPageFlag } = scope.state;

    for (var i of manipulation) {
        let { slave, pose, trigger, show } = i;
        let location = slave.split('.');

        // 模块被操控: module
        // 字段被操控: module.enname
        let form = location[0];
        let itemname = location[1];
        let display = ((data[0] && data[0][trigger] === pose) ? (!show) : show);

        if (form && itemname) {
            Pool[form].Field.map((currenItem) => {
                if (currenItem.enname === itemname) {
                    currenItem.hidepage[btnPageFlag] = display;
                }
            })
        }
        else if (form) {
            Pool[form].hidepage[btnPageFlag] = display;
        }
    }
    let param = {};
    param[Pool] = Pool
    scope.setState(param);
}

export const onChangeSelect = (self, selectItem, item, childType) => {
    let nameValue = selectItem.props.children == "请选择" ? "" : selectItem.props.children;
    let idValue = selectItem.props.id || "";
    let { codename, enname, showname } = item;
    if (childType && childType.search("DataHeader") == -1) {
        codename = childType + "." + codename;
        enname = childType + "." + enname;
        showname = childType + "." + showname;
    }
    let param = {}
    param[showname] = nameValue;
    param[enname] = idValue;
    self.props.form.setFieldsValue(param);
}

/**
 * 根据一个字段特定的值影响另外一个字段的显示隐藏
 * value 当前操作的特定字段选中或者输入的值
 * showcontrol initTemplate配置里的showcontrol
 * btnPageFlag 当前页面码0新增 1编辑 2详情 3复制
 * FormField initTemplate的
 * FormTableField initTemplate的
 * childTableColumn initTemplate的
 */
export const showFieldControlCommon = (value, showcontrol, btnPageFlag, FormField, FormTableField, childTableColumn) => {
    if (!value || !showcontrol) return;
    let layer, changeField, reginValue, controlFiels;
    showcontrol.forEach((controlItem) => {
        reginValue = controlItem.value || "";
        controlFiels = controlItem.fields;
        layer = controlItem.layer;
        //获取export出来的具体值
        switch (layer) {
            case "FormField":
                changeField = FormField;
                break;
            case "FormTableField":
                changeField = FormTableField;
                break;
            case "childTableColumn":
                changeField = childTableColumn;
                break;
        }
        //获取到具体的要显示item
        controlFiels.map((fielditem) => {
            changeField = changeField[fielditem];
        })

        if (!changeField.hidepage) {
            changeField.hidepage = {};
        }

        if (value == reginValue) {
            changeField.hidepage[btnPageFlag] = false;
        } else {
            changeField.hidepage[btnPageFlag] = true;
        }
    })
}

export const setFieldRequireCommon = (value, requirecontrol, self) => {
    if (!value || !requirecontrol) return;
    let { childTableColumn, FormField, FormTableField } = self.state;
    let layer, changeField, reginValue, controlFiels;
    requirecontrol.forEach((controlItem) => {
        reginValue = controlItem.value;
        controlFiels = controlItem.fields;
        layer = controlItem.layer;
        //获取export出来的具体值
        switch (layer) {
            case "FormField":
                changeField = FormField;
                break;
            case "FormTableField":
                changeField = FormTableField;
                break;
            case "childTableColumn":
                changeField = childTableColumn;
                break;
        }
        //获取到具体的要显示item
        controlFiels.map((fielditem) => {
            changeField = changeField[fielditem];
        })

        if (value == reginValue) {
            changeField.required = true;
        } else {
            changeField.required = false;
        }
    })
    self.setState({ FormField, FormTableField, childTableColumn });
}


export const setFieldRequireCommonForPop = (value, requirecontrol, self, FormTableField) => {
    if (!value || !requirecontrol) return;
    let changeField, reginValue, controlFiels;
    requirecontrol.forEach((controlItem) => {
        reginValue = controlItem.value;
        controlFiels = controlItem.fields;
        //获取export出来的具体值
        changeField = FormTableField;
        //获取到具体的要显示item
        controlFiels.map((fielditem) => {
            changeField = changeField[fielditem];
        })

        if (value == reginValue) {
            changeField.required = true;
        } else {
            changeField.required = false;
        }
    })
    self.setState({ FormField, FormTableField, childTableColumn });
}


export const showFieldControlCommonFormBaseInputNumber = (value, showcontrol, btnPageFlag, self) => {
    let { FormField, FormTableField, childTableColumn } = self.state;
    if (!showcontrol) return;
    let layer, changeField, reginValue, controlFiels, ishide, controlhide;
    showcontrol.forEach((controlItem) => {
        reginValue = controlItem.value || "";
        controlFiels = controlItem.fields;
        layer = controlItem.layer;
        //获取export出来的具体值
        switch (layer) {
            case "FormField":
                changeField = FormField;
                break;
            case "FormTableField":
                changeField = FormTableField;
                break;
            case "childTableColumn":
                changeField = childTableColumn;
                break;
        }
        //获取到具体的要显示item
        controlFiels.map((fielditem) => {
            changeField = changeField[fielditem];
        })

        if (!changeField.hidepage) {
            changeField.hidepage = {};
        }
        if (value) {
            changeField.hidepage[btnPageFlag] = true;
        } else {
            changeField.hidepage[btnPageFlag] = false;
        }

    })
    self.setState({ FormField, FormTableField, childTableColumn });
}
export const showFieldControlCommonFormBase = (value, showcontrol, btnPageFlag, self) => {

    let { childTableColumn, FormField, FormTableField } = self.state;
    // if(typeof(value) != "number" && !value) return;
    if (!showcontrol) return;
    let layer, changeField = {}, reginValue, controlFiels, ishide;
    showcontrol.forEach((controlItem) => {
        reginValue = controlItem.value || "";
        controlFiels = controlItem.fields;
        layer = controlItem.layer;
        if (controlItem.ishide) {
            ishide = controlItem.ishide;
        } else {
            ishide = "false";
        }
        //获取export出来的具体值
        switch (layer) {
            case "FormField":
                changeField = FormField;
                break;
            case "FormTableField":
                changeField = FormTableField;
                break;
            case "childTableColumn":
                changeField = childTableColumn;
                break;
        }
        //获取到具体的要显示item
        controlFiels.map((fielditem) => {
            changeField = changeField[fielditem];
        })

        if (!changeField.hidepage) {
            changeField.hidepage = {};
        }

        if (reginValue == value || reginValue.toString().search(value) != -1) {
            changeField.hidepage[btnPageFlag] = false;
        } else {
            changeField.hidepage[btnPageFlag] = true;
        }

    })
    self.setState({ FormField, FormTableField, childTableColumn });
}



/**
 * 小数型精度控制
 * 
*/

export const getPrecision = (number, limit) => {
    if (!number) return;
    let fraction = number.split('.');
    let decimalPart = fraction[1];

    if (!decimalPart) return;
    let len = decimalPart.length;
    return ((len < limit) ? len : limit);
}

//拼接下级级联的上级参数值
export const CalcuParmForRef = (item, data, self, resetFlag, dataObj) => {
    let { refStateParam } = self.state;
    let tempParam;
    if (!item.cascadeName) return;

    if (isEmptyObj(item.cascadeName)) {
        let temp = [];
        temp.push(item.cascadeName);
        item.cascadeName = temp;
    }
    let _thisParmField;

    item.cascadeName.map((itemcas) => {
        let { paramkey, offers, childtype, refKey, resetOffers = true } = itemcas;
        tempParam = {};
        if (refKey && dataObj) {
            data = dataObj[refKey];
        }
        //待优化 先取一个级联参数
        tempParam[paramkey] = data || null;
        //param 配置数据里的固定参数
        //tempParam 依赖字段计算出来的参数
        //tempParam = Object.assign({}, param, tempParam);
        _thisParmField = `${item.enname}_${childtype}_${offers}`;
        refStateParam[_thisParmField] = tempParam;
        if (offers && resetFlag && resetOffers) {
            let param = {}
            param[offers] = null;
            //重置级联下级参照值
            self.props.form.setFieldsValue(param);
        };
    })



    self.setState({ refStateParam });
}

export const getUUI = () => {
    axios({
        method: "get",
        url: "/occ-base/base/goods/get-uuid",
    }).then(function(res){
        sessionStorage.setItem("uui",res.data);
    }).catch(function (err) {
        console.log("获取uui失败!");
    });
}

export const onEditGridValidate = (field, fields, index, title) => {
    let errorFields = sessionStorage.getItem("errorFields");
    if (!errorFields || errorFields == "null") {
        errorFields = {};
    } else {
        errorFields = JSON.parse(errorFields);
    }
    errorFields[`${index + 1}${title}`] = fields;

    sessionStorage.setItem("errorFields", JSON.stringify(errorFields));
};

export const renderSelectInit = (data, defaultValue) => {
    if (typeof (data) == "number") {
        return data.toString();
    }
    if (!data) return defaultValue || "";
    return data;
}

export const dealMoney = (value, precision = 8) => {
    let mi = Math.pow(10, precision)
    value = Math.round(value * mi) / mi;
    return value;
}

export const toThousands = (value, precision = 4) => {
    if (value == 0) return value;
    if (precision) {
        let mi = Math.pow(10, precision)
        value = Math.round(value * mi) / mi;
    }
    var reg = String(value).indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g;//千分符的正则
    let StringValue = String(value).replace(reg, '$1,')

    return StringValue;
}

export const dealApproalData = (data) => {
    let list = [];
    if (data.length == 0) return;
    data.map((ele, index) => {
        if (list.length <= 0) {
            list.push({
                billtypename6: ele.billtypename6,
                approvelink: ele.approvelink,
                key: index + 1,
                children: [ele]
            })
        } else {
            let child = list.find(item => {
                return item.approvelink == ele.approvelink && item.billtypename6 == ele.billtypename6;
            })

            if (child) {
                child.children.push(ele)
            } else {
                list.push({
                    approvelink: ele.approvelink,
                    billtypename6: ele.billtypename6,
                    key: index + 1,
                    children: [ele]
                })
            }
        }

    })
    console.log("list", list);
    return deepClone(list)
}

export const renderRadioInit = (data, defaultValue) => {
    if (typeof (data) == "number") {
        return data;
    }
    if (!data) return defaultValue || 0;
    return data;
}

//销售订单氯碱部门
export const showControlForm = (value, showcontrol, btnPageFlag, self) => {
    let { childTableColumn, FormField, FormTableField } = self.state;
    if (!showcontrol) return;
    let layer, changeField = {}, reginValue, controlFiels, ishide;
    showcontrol.forEach((controlItem) => {
        reginValue = controlItem.value || "";
        controlFiels = controlItem.fields;
        layer = controlItem.layer;
        if (controlItem.ishide) {
            ishide = controlItem.ishide;
        } else {
            ishide = "false";
        }
        switch (layer) {
            case "FormField":
                changeField = FormField;
                break;
            case "FormTableField":
                changeField = FormTableField;
                break;
            case "childTableColumn":
                changeField = childTableColumn;
                break;
        }
        controlFiels.map((fielditem) => {
            changeField = changeField[fielditem];
        })
        if (!changeField.hidepage) {
            changeField.hidepage = {};
        }
        if (reginValue == value) {
            changeField.hidepage[btnPageFlag] = false;
        } else {
            changeField.hidepage[btnPageFlag] = true;
        }

    })
    self.setState({ FormField, FormTableField, childTableColumn });
}


export const showFieldControlCommonFor1909 = (controlData, itemfield, btnPageFlag, self, initFlag, bakInitFormObj) => {
    let { showcontrol } = itemfield;
    if ((!controlData || !showcontrol) && controlData !== 0) return;
    let { childTableColumn, FormField, FormTableField } = self.state;
    if (!showcontrol) return;
    let layer, changeField = {}, reginValue, controlFiels, matchValue;

    showcontrol.forEach((controlItem) => {
        reginValue = controlItem.value || "";
        controlFiels = controlItem.fields;
        layer = controlItem.layer;
        //获取export出来的具体值
        layer.map((item, index) => {
            if (index == 0) {
                switch (item) {
                    case "FormField":
                        changeField = FormField;
                        if (!isEmptyObj(changeField)) {
                            changeField = bakInitFormObj.bakFormField
                        }
                        break;
                    case "FormTableField":
                        changeField = FormTableField;
                        if (!isEmptyObj(changeField)) {
                            changeField = bakInitFormObj.bakFormTableField
                        }
                        break;
                    case "childTableColumn":
                        changeField = childTableColumn;
                        if (!isEmptyObj(changeField)) {
                            changeField = bakInitFormObj.bakchildTableColumn
                        }
                        break;
                }
            } else {
                changeField = changeField[item];
            }
        })


        if (itemfield.type == "RefComponent") {
            matchValue = typeof initFlag == "boolean" ? controlData[controlItem.dtoKey] : controlData[controlItem.refKey]
        } else {
            matchValue = typeof initFlag == "boolean" ? controlData[controlItem.dtoKey] : controlData
        }
        if (typeof controlItem.hideFlag != "boolean") {
            controlItem.hideFlag = false
        }
        if (typeof matchValue == "number") {
            matchValue = matchValue.toString();
        }

        if (controlFiels == "all") {
            if (!changeField.hidepage) changeField.hidepage = {};
            if (reginValue == matchValue || (matchValue && reginValue.toString().search(matchValue) != -1)) {
                changeField.hidepage[btnPageFlag] = controlItem.hideFlag;
            } else {
                changeField.hidepage[btnPageFlag] = !controlItem.hideFlag;
            }
        } else {
            changeField.map(item => {
                if (!item.hidepage) {
                    item.hidepage = {};
                }
                if (controlFiels.indexOf(item.enname || item.dataIndex) !== -1) {
                    if (reginValue == matchValue || (matchValue && reginValue.toString().search(matchValue) != -1)) {
                        item.hidepage[btnPageFlag] = controlItem.hideFlag;
                    } else {
                        item.hidepage[btnPageFlag] = !controlItem.hideFlag;
                    }
                }

            })
        }

    })

    self.setState({ FormField, FormTableField, childTableColumn });

    typeof initFlag === "string" && EmptyRowDataField(controlData, itemfield, self.props.rowData, initFlag, self,childTableColumn,btnPageFlag)

}
export const EmptyRowDataField = (controlData, itemfield, rowData, model, self,childTableColumn,btnPageFlag) => {
    let { showcontrol } = itemfield;
    if ((!controlData || !showcontrol) && controlData !== 0) return;
    if (!showcontrol) return;
    let { FormField } = self.state;
    let layer, reginValue, controlFiels, enname, matchValue, deleteField, str;
    showcontrol.forEach((controlItem) => {
        reginValue = controlItem.value;
        controlFiels = controlItem.fields;
        enname = controlItem.dtoKey;
        layer = controlItem.layer[1];


        if (layer.search("DataHeader") != -1) {
            if (controlFiels == "all") {
                controlFiels = FormField[layer].Field;
            }
            matchValue = itemfield.type == "RefComponent" ? controlData[controlItem.refKey] : controlData;
            if ((reginValue.toString().search(matchValue) == -1 && !controlItem.hideFlag)
                || (reginValue.toString().search(matchValue) !== -1 && controlItem.hideFlag)) {
                controlFiels.map(item => {
                    deleteField = item;
                    if (controlItem.fields === "all") deleteField = item.enname;
                    delete rowData[deleteField];
                    let str = deleteField.slice(0, deleteField.length - 2);
                    delete rowData[`${str}Name`];
                    delete rowData[`${str}Code`];
                    delete rowData[`${str}Id`];

                })
                actions[model].updateState({ rowData: rowData });
            }
        }else if(rowData && rowData[layer]) {
            let showFileds = controlItem.fields;
            let childTable = layer;
            rowData = hideColumnCommon(childTable,self,childTableColumn,btnPageFlag);
        }
    })
    actions[model].updateState({ rowData: rowData });
}

const hideColumnCommon = (childTable,self,childTableColumn,btnPageFlag) => {
    let {rowData} = self.props;
    childTableColumn[childTable].column.map(column => {
        if(!column.hidepage) column.hidepage = {};
        if(column.hidepage[btnPageFlag]) {
            rowData[childTable].map((item,index)=> {
                let f = column.dataIndex;
                if(column.renderType == "refcomponent" || column.renderType == "select"){
                    let str = f.slice(0, f.length - 4);
                    delete item[`${str}Id`];
                    delete item[`${str}Name`];
                    delete item[`${str}Code`];
                }else {
                    delete item[f];
                }
            })
        };
    })
    return rowData;
    // this.setState(childTableColumn);
    // actions.SalesOrderMonitorSample.updateState({ rowData: rowData });
}
export const setFieldRequireCommonFor1909 = (controlData, itemfield, self, initFlag, bakInitFormObj) => {
    let { requirecontrol } = itemfield;
    if (!requirecontrol && controlData !== 0) return;
    let { childTableColumn, FormField, FormTableField } = self.state;
    let layer, changeField, reginValue, controlFiels, matchValue;
    requirecontrol.forEach((controlItem) => {
        reginValue = controlItem.value;
        controlFiels = controlItem.fields;
        layer = controlItem.layer;
        layer.map((item, index) => {
            if (index == 0) {
                switch (item) {
                    case "FormField":
                        changeField = FormField;
                        if (!isEmptyObj(changeField)) {
                            changeField = bakInitFormObj.bakFormField
                        }
                        break;
                    case "FormTableField":
                        changeField = FormTableField;
                        if (!isEmptyObj(changeField)) {
                            changeField = bakInitFormObj.bakFormTableField
                        }
                        break;
                    case "childTableColumn":
                        changeField = childTableColumn;
                        if (!isEmptyObj(changeField)) {
                            changeField = bakInitFormObj.bakchildTableColumn
                        }
                        break;
                }
            } else {
                changeField = changeField[item];
            }

        })
        //获取export出来的具体值

        //获取到具体的要显示item
        // controlFiels.map((fielditem) => {
        //     changeField = changeField[fielditem];
        // })

        if (itemfield.type == "RefComponent") {
            if (!controlData) controlData = [];
            matchValue = typeof initFlag == "boolean" ? controlData[controlItem.dtoKey] : controlData[controlItem.refKey];
        } else {
            matchValue = typeof initFlag == "boolean" ? controlData[controlItem.dtoKey] : controlData;
        }

        if (typeof controlItem.hideFlag != "boolean") {
            controlItem.requireFlag = true;
        }

        changeField.map(item => {
            if (controlFiels.indexOf(item.enname || item.dataIndex) !== -1) {
                if (matchValue == reginValue || (matchValue && reginValue.toString().search(matchValue) != -1)) {
                    item.required = controlItem.requireFlag;
                } else {
                    item.required = !controlItem.requireFlag;
                }
            }
        })
    })
    self.setState({ FormField, FormTableField, childTableColumn });
}

//拼接下级级联的上级参数值
export const CalcuParmForRef1909 = (controlData = {}, itemfield, self, initFlag, bakInitFormObj) => {
    let { cascadeName } = itemfield;
    if ((!cascadeName) && controlData !== 0) return;
    let { refStateParam } = self.state;
    let tempParam, _thisParmField, matchValue;

    if (isEmptyObj(itemfield.cascadeName)) {
        let temp = [];
        temp.push(itemfield.cascadeName);
        itemfield.cascadeName = temp;
    }

    itemfield.cascadeName.map((controlItem) => {
        let { paramkey, offers, childtype, resetOffersFlag = true } = controlItem;
        tempParam = {};


        if (itemfield.type == "RefComponent") {
            matchValue = typeof initFlag == "boolean" ? controlData[controlItem.dtoKey] : controlData[controlItem.refKey];
        } else {
            matchValue = typeof initFlag == "boolean" ? controlData[controlItem.dtoKey] : controlData;
        }

        tempParam[paramkey] = matchValue;
        //param 配置数据里的固定参数
        //tempParam 依赖字段计算出来的参数
        //tempParam = Object.assign({}, param, tempParam);
        _thisParmField = `${itemfield.enname}_${childtype}_${offers}`;
        refStateParam[_thisParmField] = tempParam;
        if (offers && resetOffersFlag && typeof initFlag !== "boolean") {
            let param = {}
            param[offers] = null;
            //重置级联下级参照值
            self.props.form.setFieldsValue(param);
        };
    })



    self.setState({ refStateParam });
}

export const ControlCommonFor1909 = (controlData, itemfield, btnPageFlag, self, initFlag, bakInitFormObj) => {
    if (itemfield.showcontrol) {
        showFieldControlCommonFor1909(controlData, itemfield, btnPageFlag, self, initFlag, bakInitFormObj);
    }
    if (itemfield.requirecontrol) {
        setFieldRequireCommonFor1909(controlData, itemfield, self, initFlag, bakInitFormObj);
    }

    if (itemfield.cascadeName) {
        CalcuParmForRef1909(controlData, itemfield, self, initFlag, bakInitFormObj);
    }
}